package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.CookieData;
import bsi.vn.Data.TicketAdapter;
import bsi.vn.Data.TicketData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

@SuppressLint("ValidFragment")
public class TicketResultSearchFragment extends Fragment {
	private ArrayList<TicketData> ticketData = new ArrayList<TicketData>();
	private Context _context;
	ListView lvTicket;

	public TicketResultSearchFragment()
	{}

	public TicketResultSearchFragment(Context context) {
		_context = context;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_ticketsearchresult, container, false);
		
		return rootView;
	}
	
	private class myAsyncTask extends AsyncTask<String, String, String>    {
    	
    	@Override 	
		protected String doInBackground(String... params) {
    		String data = "";
			try {
				
				data = GetTicket();
		    } 
			catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}
		
		@Override
		protected void onPostExecute(String result) {
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]); 
			if (loc_iResponseCode == Consts.RC_LOGOUT)
			{
				startActivity(new Intent(_context, LoginActivity.class));
				return;
			}
			if ( loc_iResponseCode == Consts.RC_ERROR)
			{
				ProcessFunc.ShowSimpleDialog(_context, "Error", loc_arResponse[1]);
				return;
			}
			try{
	        	JSONArray jArray = new JSONArray(loc_arResponse[1]);
	        	for(int i=0;i<jArray.length();i++){
	        		JSONObject json_data = jArray.getJSONObject(i);
	        		TicketData ticket = new TicketData();
	        		ticket.setTicketId(json_data.getInt(Consts.SDB_TICKETID));
	        		ticket.setTicketCode(json_data.getString(Consts.SDB_TICKETCODE));
	        		ticket.setATMId(json_data.getInt(Consts.SDB_ATMID));
	        		ticket.setSerialNo(json_data.getString(Consts.SDB_SERIALNO));
	        		ticket.setProvince(json_data.getString(Consts.SDB_PROVINCE));
	        		ticketData.add(ticket);
	        	}
	    	}
	        catch(JSONException e){
	        	Log.e("log_tag", "Error parsing data "+e.toString());
	        }
			
			lvTicket.setAdapter(new TicketAdapter(_context, ticketData));
	        
			lvTicket.setOnItemClickListener(new OnItemClickListener() {
    			@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				int TicketId = ticketData.get(position).getTicketId();
    				Intent i = new Intent(_context, TicketDetailActivity.class);
    				i.putExtra("TicketId", TicketId);
    	            startActivity(i);
    			}
    		});
		}
		
        @Override
        protected void onPreExecute() {
       }
        
        @Override
        protected void onProgressUpdate(String... text) {
        }
 	}

    private String GetTicket() {
    	InputStream is = null;
    	String result = "";
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(Consts.MAIN_URL);
    		
    		CookieData cookie = ProcessFunc.GetCookie(_context);
    		
    		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
            nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC, Consts.F_TICKETLIST));
            nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String.valueOf(cookie.getUserId())));
            nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE,cookie.getCookie()));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}
    	catch(Exception e){
    		Log.e("log_tag", "Error in http connection "+e.toString());
    	}

        try{
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
	    	StringBuilder sb = new StringBuilder();
	    	String line = null;
	    	while ((line = reader.readLine()) != null) {
	    		sb.append(line + "\n");
	    	}
	    	is.close();
	    	result = sb.toString();
        }
		catch(Exception e){
	    	Log.e("test", "Error converting result "+e.toString());
	    }
        return result;
    } 
}

